<template>
  <div class="home">
    <el-upload
        ref="upload"
        drag
        class="upload-demo"
        action="#"
        accept="image/jpeg,image/jpg,image/png,image/bmp,image/x-icon,image/webp"
        :limit="1"
        :on-preview="handlePreview"
        :on-remove="handleRemove"
        :file-list="fileList"
        :auto-upload="false"
        :before-upload="beforeUpload"
        :http-request="uploadHttpRequest"
    >
      <el-icon class="el-icon-upload" :size="200"><UploadFilled /></el-icon>
      <div class="el-upload__text">
        将文件拖到此处，或<em style="color: #409eff">点击上传</em>
      </div>
    </el-upload>
    <div slot="tip" class="el-upload__tip">
        <a>注:文件大小不超过10M!</a>
    </div>
    <el-progress
      v-if="processVisible"
      :percentage="processPercent"
      :text-inside="true"
      :stroke-width="24"
      :status="processStatus"
      style="margin: 20px 0;"
    />
    <el-alert
      v-if="tipVisible"
      :title="tipTitle"
      type="error"
      @close="tipVisible = false"
    />
    <el-button
      class="upload-click"
      size="small"
      type="primary"
      :loading="uploading"
      @click="submitUpload"
    >
      <el-icon><Upload /></el-icon>
      上传到服务器
    </el-button>
    <el-button
      class="cancel-click"
      size="small"
      @click="cancelUpload"
    >
      <el-icon><CircleClose /></el-icon>
      取&nbsp;&nbsp;消
    </el-button>
    <div class="understand">
      <p>·可上传图片格式: jpeg, jpg, png,bmp, x-icon, webp。范围外的图片格式暂时无法上传, 请将图片格式改为范围内格式再上传。</p>
      <p>·图片上传后请在“查看结果”中进行查询。</p>
    </div>
  </div>
</template>

<script>
export default {
  props: {
    title: {
      type: String,
      default: "上传文件"
    },
    upLoadVisible: {
      type: Boolean,
      default: false
    },
    uploadUrl: { // 上传文件的api
      type: String,
      default: "http://www.ai666.site:8799/result"
    }
  },
  data() {
    return {
      fileList: [],
      uploading: false,
      processPercent: 5,
      processStatus: 'success',
      processVisible: false,
      tipVisible: false,
      tipTitle: '',
      timer: null
    };
  },
  methods: {
    // 上传文件之前的钩子：判断上传文件格式、大小等，若返回false则停止上传
    beforeUpload(file) {
      // 文件类型
      const isType = file.type === "image/png"||"image/jpg"||"image/jpeg"||"image/bmp"||"image/x-icon";
      const isTypeComputer =
        file.type ===
        "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
      const fileType = isType || isTypeComputer;
      if (!fileType) {
        this.$message.error("上传文件只能是图片格式！");
      }
  
      // 文件大小限制为10M
      const fileLimit = file.size / 1024 / 1024 < 10;
      if (!fileLimit) {
        this.$message.error("上传文件大小不超过10M！");
      }
      return fileType && fileLimit;
    },
    // 自定义上传方法，param是默认参数，可以取得file文件信息，具体信息如下图
    async uploadHttpRequest(param) {
      const that = this;
      this.uploading = true; // 显示按钮加载中
      this.processVisible = true; // 显示进度条
      this.processPlus();
      // FormData对象，添加参数只能通过append('key', value)的形式添加
      const formData = new FormData();
      // 添加文件对象
      formData.append("file", param.file);
  
      const config = {
        headers: {
          "Content-Type": "multipart/form-data"
        }
      };
      this.axiosUpload.post(this.uploadUrl, formData, config).then(res => {
        // 这里的res需根据后台返回情况判断
        if (res.data.code === 200) {
          this.processPercent = 100;
          that.uploading = false;
          this.processVisible = false;
          this.timer = null;
          that.$emit("closeUpload");
          that.$message.success(res.data.msg);
        } else {
          this.processPercent = 100;
          this.processStatus = "exception";
          this.tipVisible = true;
          this.tipTitle = res.data.msg;
          this.uploading = false;
        }
      }).catch(reject => {
        console.log(reject)
      })
    },
    // 上传至服务器
    submitUpload() {
      this.$refs.upload.submit();
    },
    handleRemove(file, fileList) {
      console.log(file, fileList);
    },
    handlePreview(file) {
      console.log(file);
    },
    cancelUpload() {
      this.$refs.upload.clearFiles(); // 清除上传文件对象
      this.fileList = []; // 清空选择的文件列表
      this.$emit("closeUpload");
    },
    // 前期进度条增加
    processPlus() {
      this.timer = setInterval(() => {
        if (this.processPercent < 90) {
          this.processPercent += 10;
        }
      }, 200)
    },
    closeDialog() {
      this.$emit('closeUploadDialog');
    }
  }
};
</script>

<style scoped>
.el-upload {
  width: 100%;
}

.upload__demo {
  width: 600px;
  height: 200px;
}

.el-upload__text {
  width: 600px;
}

.el-upload__tip {
  margin-bottom: 20px;
}

.el-upload__tip  a {
  color: #b20000;
  padding: 6px;
  background-color: #5ba58ae8;
  font-family: SimSun;
  font-size: 14px;
  font-weight: bold;
}

.upload-click {
  width: 120px;
  height: 30px;
  margin-right: 20px;
  font-size: 16px;
  font-family: SimSun;
}

.cancel-click {
  width: 120px;
  height: 30px;
  text-align: center;
  vertical-align: middle;
  font-size: 16px;
  font-family: SimSun;
}

.understand {
  position: relative;
  left: 5%;
  width: 90%;
  height: 250px;
  margin-top: 50px;
  background-color: #f3c097;
  border-radius: 4px;
  font-family: SimSun;
  font-size: 20px;
  padding: 10px 20px 10px 20px;
  text-align: left;
}
</style>